package zh.cgserver.core;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;

public class ClientHandler implements Runnable{
    Socket socket ;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try {
            //1.解析请求行
            HttpServleRequest httpServleRequest = new HttpServleRequest(socket);
            //2.分析请求
            String path = httpServleRequest.getUrl();
            File root = new File(ClientHandler.class.getClassLoader().getResource(".").toURI()) ;
            File staticDir = new File(root,"zhstatic");
            File  file = new File(staticDir,path);
            System.out.println("文件是否存在:"+file.exists());
            int statusCode ;//状态代码
            String statusReason ;//状态描述
            if(file.isFile()){
                statusCode = 200;
                statusReason = "OK";
            }else{
                statusCode = 404;
                statusReason = "NotFound";
                file = new File(staticDir,"zhroot/404.html");
            }
            //3.发送响应
            println("HTTP/1.1 " +statusCode+" "+statusReason);
            println("Content-Type: text/html");
            println("Content-Length: "+file.length());
            println("");
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            int len;
            byte[] bytes = new byte[1024];
            while((len=fis.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
        }catch (IOException | URISyntaxException e){

        }

    }
    public void println(String line) throws IOException{
        OutputStream os = socket.getOutputStream();
        byte[] data = line.getBytes(StandardCharsets.ISO_8859_1);
        os.write(data);
        os.write(13);
        os.write(10);
    }

}
